"""
@FileName：video_record.py\n
@Description：\n
@Author：锦沐Python\n
@Time：2024/8/16 14:41\n
"""

import cv2
from PIL import Image, ImageTk
from datetime import datetime

# print(cv2.getBuildInformation())


class VideoRecord:
    """
    控制本地编号为 0 的摄像机进行录制，
    并将画面实时渲染到 canvas 上，
    录制结束保存为 mp4 格式
    """
    def __init__(self, canvas, save_path):
        self.canvas = canvas
        # 保存路径
        self.save_path = save_path
        # 录制中
        self.is_recording = False
        # 图片对象
        self.photo = None
        self.vid_camera = None
        self.video_writer = None

    def start_record(self):
        """
        开启摄像头进行采集
        XVID ： avi
        mp4v : mp4
        """
        if self.vid_camera:
            return

        self.vid_camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        # print(self.vid_camera.isOpened())
        self.is_recording = True
        if self.save_path:
            # 设置视频编解码器和输出文件, 此处编辑器无法识别不用管
            fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            # 获取图像
            # 获取图像大小
            frame_size = (int(self.vid_camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
                          int(self.vid_camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))

            file_name = self.save_path / f"record_{datetime.now().strftime('%m-%d_%H-%M-%S')}.mp4"
            # 创建写入对象
            self.video_writer = cv2.VideoWriter(file_name, fourcc, 30, frame_size)

    def update(self):
        """
        更新页面，保存视频
        此处必须先保存后再显示
        """
        if self.is_recording:
            ret, frame = self.vid_camera.read()

            if self.video_writer:
                self.video_writer.write(frame)

            if ret:
                frame = cv2.resize(frame, (self.canvas.winfo_width(), self.canvas.winfo_height()))
                self.photo = ImageTk.PhotoImage(image=Image.fromarray(frame))
                # 只更新图像，不清除整个画布
                self.canvas.create_image(0, 0, image=self.photo, anchor="nw")

    def pause_record(self):
        """
        暂停录制
        """
        self.is_recording = False

    def resume_record(self):
        """
        继续录制
        """
        self.is_recording = True

    def end_record(self):
        """
        停止录制
        """
        if self.vid_camera:
            self.pause_record()
            self.vid_camera.release()
            if self.video_writer:
                self.video_writer.release()

            self.vid_camera = None
